﻿using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using AutoMapper;
using BestTrader.Cms.Core.Models;
using BestTrader.Cms.IServices;
using BestTrader.Cms.ViewModels;
using BestTrader.Cms.ViewModels.WebApi;
using BestTrader.Cms.WebApi.Common;
using BestTrader.Cms.WebApi.Validation;
using FluentValidation.Results;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace BestTrader.Cms.WebApi.Controllers.v1
{
    /// <summary>
    /// [10000] 登录管理
    /// </summary>
    [ApiVersion("1.0")]
    [Route("api/v{version:apiVersion}/[controller]")]
    [ApiController]
    public class AccountController : BaseController
    {
        #region BASE

        private readonly IManagerService _service;
        private readonly IQiniuService _qiniuService;
        private readonly IMapper _mapper;
        private readonly IConfiguration _configuration;
        private readonly IVideoService _videoService;

        public AccountController(IManagerService service, IQiniuService qiniuService, IMapper mapper, IConfiguration configuration, IVideoService videoService)
        {
            _service = service;
            _qiniuService = qiniuService;
            _mapper = mapper;
            _configuration = configuration;
            _videoService = videoService;
        }

        #endregion

        /// <summary>
        /// [10001] 登录
        /// </summary>
        /// <param name="input">登录实体</param>
        /// <remarks>
        /// LoginInput 登录实体:
        /// INPUT: /LoginInput
        /// {
        ///     "userName": "string", // 用户名
        ///     "realName": "string", // 真实姓名
        /// }
        /// OUTPUT /LoginOutput
        /// {
        ///     "Id": "int",            // 主键
        ///     "RoleId": "int",        // 角色ID（3~5：代理；6：直客）
        ///     "UserName": "string",   // 用户名
        ///     "Avatar": "string",     // 头像
        ///     "RealName": "string",   // 真实姓名
        ///     "Mobile": "string",     // 手机号码
        ///     "Email": "string",      // 邮箱
        ///     "DeptCode": "string",   // 用户机构
        ///     "State": "int"          // 状态（0：未审核，1：通过；2：未通过）
        /// }
        /// </remarks>
        /// <returns>LoginOutput</returns>
        [HttpPost("Login")]
        public JsonResult Login(LoginInput input)
        {
            var result = _service.Login(input.UserName, input.Password);
            var data = _mapper.Map<LoginOutput>(result.Data);

            if (result.Success && result.Data !=null)
            {
                var videoState = _videoService.ValidVideo(result.Data.Id.ToString());
                data.ValidVideoState = videoState.Data;
                ///jwt token
                var claims = new[]
                {
                   new Claim(ClaimTypes.Name, input.UserName)
                };
                var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Jwt:SecurityKey"]));
                var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
                var token = new JwtSecurityToken(
                      issuer: _configuration["Jwt:Issuer"],
                      audience: _configuration["Jwt:Audience"],
                      claims: claims,
                      expires: DateTime.Now.AddMinutes(30),
                      signingCredentials: creds);
                data.Token = new JwtSecurityTokenHandler().WriteToken(token);
            }
            return Json<LoginOutput>(data, result.Success, result.ResultCode, result.ResultMsg);

        }


        /// <summary>
        /// [10002] 注册
        ///     
        /// </summary>
        /// <param name="input">注册实体</param>
        /// <remarks>
        /// INPUT: /TerminalRegisterInput
        /// {
        ///     "realName": "string",           // 真实姓名
        ///     "QQ": "string",                 // QQ
        ///     "Email": "string",              // 邮箱
        ///     "CardType": "int",              // 证件类型
        ///     "CardId": "string",             // 证件号码(身份证等等)
        ///     "Mobile": "string",             // 手机号码
        ///     "BankType": "string",           // 银行类型
        ///     "BankProvince": "string",       // 银行省份
        ///     "BankCity": "string",           // 银行城市
        ///     "BankCard": "string",           // 银行卡号
        ///     "InvitationCode": "string",     // 邀请码
        ///     "AuditImages": "array"          // 审核资料
        /// }
        /// OUTPUT: /TerminalRegisterOutput
        /// {
        ///     "userName": "string",           // （直客）用户名
        ///     "password": "string",           // （直客）密码
        /// }
        /// </remarks>
        /// <returns>TerminalRegisterOutput</returns>
        [HttpPost("Register")]
        public JsonResult TerminalRegister(TerminalRegisterInput input)
        {
            var result = new BaseResult { Success = false };
            var data = new TerminalRegisterOutput();
            ManagerTerminalRegisterValidation validation = new ManagerTerminalRegisterValidation();
            ValidationResult results = validation.Validate(input);

            if (results.IsValid)
            {
                var param = _mapper.Map<ManagerTerminalRegisterModel>(input);
                param.Reg = input.InvitationCode;
                param.Source = "App";
                var resultData = _service.AddTerminal(param);
                data = _mapper.Map<TerminalRegisterOutput>(resultData.Data);
                result.Success = true;
            }
            else
            {
                result.ResultCode = ResultCodeAddMsgKeys.CommonModelStateInvalidCode;
                result.ResultMsg = results.ToString("||");
            }

            return Json<TerminalRegisterOutput>(data, result.Success, result.ResultCode, result.ResultMsg);
        }

        /// <summary>
        /// [10003] 注册资料(上传)
        /// </summary>
        /// <param name="input">文件上传</param>
        /// <remarks>
        /// INPUT: /FileData
        /// {
        ///     "FormFileCollection": "array[formData]",    // 文件集合
        ///     "FormFile": "formData",                     // 文件
        /// }
        /// OUTPUT: /RegisterDataOutput
        /// {
        ///     "ImageUrl": "string",                       // 图片
        ///     "ImageUrls": "array[string]",               // 图片集合
        /// }
        /// </remarks>
        /// <returns>RegisterDataOutput</returns>
        //[AllowAnonymous]
        [HttpPost("Files")]
        [ProducesResponseType(200)]
        [Authorize]
        public async Task<JsonResult> RegisterDataAsync([FromForm]FileData input)
        {
            if (input.FormFile == null && input.FormFileCollection == null)
            {
                return Json<RegisterDataOutput>(null, false, 601, "请选择您要上传的文件!");
            }

            UploadQiniuData file = null;
            List<UploadQiniuData> files = new List<UploadQiniuData>();
            if (input.FormFile != null)
            {
                file = await _qiniuService.UploadFileAsync(input.FormFile);
            }
            if (input.FormFileCollection != null)
            {
                files = await _qiniuService.UploadFilesAsync(input.FormFileCollection);
            }

            var data = new RegisterDataOutput
            {
                ImageUrl = file?.Key,
                ImageUrls = files.Select(p => p.Key)
            };
            return Json<RegisterDataOutput>(data);
        }
        /// <summary>
        /// [10004] 修改密码
        /// </summary>
        /// <returns></returns>
        [HttpPost("ModifyPassword")]
        [Authorize]
        public JsonResult ModifyPassword(ModifyPasswordInput input)
        {
            var result = new BaseResult { Success = false };
            var model = _mapper.Map<PasswordModel>(input);
            result.Success = false;
            PasswordModelValidation validation = new PasswordModelValidation();
            ValidationResult results = validation.Validate(model);
            if (results.IsValid)
            {
                result = _service.EditPassword(model);
                result.Success = true;
            }
            else
            {
                result.ResultCode = ResultCodeAddMsgKeys.CommonModelStateInvalidCode;
                result.ResultMsg = results.ToString("||");
            }
            var data = _mapper.Map<ModifyPasswordOutput>(result);

            return Json<ModifyPasswordOutput>(data, result.Success, result.ResultCode, result.ResultMsg);
        }

        /// <summary>
        /// [10005] 个人信息
        /// </summary>
        /// <remarks>
        /// GetUserInfo 个人信息:
        /// INPUT: /ManagerIdInput
        /// {
        ///     "Id": "27", // 用户Id
        /// }
        /// OUTPUT /ManagerInfoOutput
        /// {
        ///     "Id": "int",            // 主键
        ///     "RoleId": "int",        // 角色ID（3~5：代理；6：直客）
        ///     "UserName": "string",   // 用户名
        ///     "Avatar": "string",     // 头像
        ///     "RealName": "string",   // 真实姓名
        ///     "Mobile": "string",     // 手机号码
        ///     "Email": "string",      // 邮箱
        ///     "DeptCode": "string",   // 用户机构
        ///     "State": "int" ,         // 状态（0：未审核，1：通过；2：未通过）
        ///     "IsLock":"bool",         //是否锁定（0：否，1：是）
        ///     "BankType":"string",     //银行卡类型
        ///     "BankProvince":"string", //银行省份
        ///     "BankCity":"string",     //银行城市
        ///     "BankCard":"string",     //银行卡号
        ///     "CardType":"int",        //证件类型（0:身份证，1：护照）
        ///     "CardId":"string",       //证件卡号
        /// }
        /// </remarks>
        /// <returns>GetUserInfo</returns>
        [HttpPost("GetUserInfo")]
        [Authorize]
        public JsonResult GetUserInfo(ManagerIdInput input)
        {

            //var result = new BaseResult();
            var resultData = _service.GetManagerById(input.Id.ToString());

            var data = _mapper.Map<ManagerInfoOutput>(resultData);
            return Json<ManagerInfoOutput>(data);
        }

        /// <summary>
        /// [10006] 个人信息修改
        /// </summary>
        /// <remarks>
        /// ModifyUserInfo 个人信息:
        /// INPUT: /ModifyUserInfoIntput
        /// {
        ///     "Id": "int",            // 主键
        ///     "RoleId": "int",        // 角色ID（3~5：代理；6：直客）
        ///     "UserName": "string",   // 用户名
        ///     "QQ": "string",         // QQ
        ///     "Avatar": "string",     // 头像
        ///     "RealName": "string",   // 真实姓名
        ///     "Mobile": "string",     // 手机号码
        ///     "Email": "string",      // 邮箱
        ///     "DeptCode": "string",   // 用户机构
        ///     "State": "int" ,         // 状态（0：未审核，1：通过；2：未通过）
        ///     "IsLock":"bool",         //是否锁定（0：否，1：是）
        ///     "BankType":"string",     //银行卡类型
        ///     "BankProvince":"string", //银行省份
        ///     "BankCity":"string",     //银行城市
        ///     "BankCard":"string",     //银行卡号
        ///     "CardType":"int",        //证件类型（0:身份证，1：护照）
        ///     "CardId":"string",       //证件卡号
        ///     "AuditImages":[],       //图片
        /// }
        /// OUTPUT /BaseResult
        /// {
        /// }
        /// </remarks>
        /// <returns></returns>
        /// 
        [HttpPost("ModifyUserInfo")]
        [Authorize]
        public JsonResult ModifyUserInfo(ModifyUserInfoIntput input)
        {

            var result = new BaseResult();
            result.Success = false;

            ModifyUserInfoModelValidation validation = new ModifyUserInfoModelValidation();
            ValidationResult results = validation.Validate(input);
            if (results.IsValid)
            {
                result = _service.AddOrModifyUserInfo(input, input.Id.ToString());
            }
            else
            {
                result.ResultCode = ResultCodeAddMsgKeys.CommonModelStateInvalidCode;
                result.ResultMsg = results.ToString("||");
            }
            return Json<Object>("", result.Success, result.ResultCode, result.ResultMsg);

        }
        /// <summary>
        ///  [10007]获取用户list
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        /// 
        [HttpPost("GetManagerList")]
        [Authorize]
        public JsonResult GetManagerList(ManagerIdAndRoleIdInput input)
        {
            var data = _service.GetCacheSubManagerByUserId(input.Id.ToString(), input.RoleId.ToString());
            return Json<Object>(data.Data, data.Success, data.ResultCode, data.ResultMsg);
        }
        /// <summary>
        /// [10008] 用户是否认证过
        /// </summary>
        /// <returns></returns>
        [HttpPost("IsValidVideo")]
        [Authorize]
        public JsonResult IsValidVideo(CurrentIdAndRoleIdInput input)
        {
            var result = new BaseResult();
            //var userId = User.Claims.FirstOrDefault(x => x.Type == "UserId")?.Value;
            var resultBool = _videoService.ValidVideo(input.CurrentId.ToString());

            return Json<Object>(resultBool, result.Success, result.ResultCode, result.ResultMsg);

        }
    }
}
